package com.hexiang.error;

import com.hexiang.domain.ResultResponse;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Optional;
import java.util.Set;

/**
 * 自定义全局异常处理
 */
@ControllerAdvice
public class CustomGlobalExceptionHandler {

    /**
     * 处理MethodArgumentNotValidException异常
     *
     * @param ex org.springframework.web.bind.MethodArgumentNotValidException
     * @return com.hexiang.domain。ResultResponse
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ResultResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {

        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder sb = new StringBuilder("");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getDefaultMessage());
        }
        String msg = sb.toString();
        return ResultResponse.error(msg);
    }

    /**
     * 处理自定义校验注解场景
     *
     * @param ex javax.validation.ConstraintViolationException
     * @return com.hexiang.domain。ResultResponse
     */
    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ResultResponse handleConstraintViolationException(ConstraintViolationException ex) {
        Set<ConstraintViolation<?>> constraintViolationSet = ex.getConstraintViolations();
        Optional<ConstraintViolation<?>> constraintViolation = constraintViolationSet.stream().findFirst();
        if (constraintViolation.isPresent()) {
            String errorMsg = constraintViolation.get().getMessageTemplate();
            return ResultResponse.error(errorMsg);
        }
        return ResultResponse.error("系统异常");
    }

}
